"""
MCP 协议实现
定义 Model Context Protocol 的核心数据结构和协议规范
"""

from dataclasses import dataclass, field
from typing import Dict, List, Optional, Union, Any
from enum import Enum
import json

class MCPAction(str, Enum):
    """MCP 请求动作类型"""
    QUERY = "query"          # 数据查询
    SCHEMA = "schema"        # 获取模式信息
    METADATA = "metadata"    # 获取元数据
    SEARCH = "search"        # 向量搜索
    STREAM = "stream"        # 流式数据
    BATCH = "batch"         # 批量操作

class MCPStatus(str, Enum):
    """MCP 响应状态"""
    SUCCESS = "success"      # 成功
    ERROR = "error"          # 错误
    PARTIAL = "partial"      # 部分成功
    PENDING = "pending"      # 处理中

@dataclass
class MCPRequest:
    """MCP 请求对象"""
    
    action: MCPAction                           # 请求动作
    query: Optional[str] = None                 # 查询语句
    parameters: Dict[str, Any] = field(default_factory=dict)  # 查询参数
    options: Dict[str, Any] = field(default_factory=dict)     # 请求选项
    
    def to_dict(self) -> Dict:
        """转换为字典格式"""
        return {
            "action": self.action.value,
            "query": self.query,
            "parameters": self.parameters,
            "options": self.options
        }
        
    @classmethod
    def from_dict(cls, data: Dict) -> "MCPRequest":
        """从字典创建请求对象"""
        return cls(
            action=MCPAction(data["action"]),
            query=data.get("query"),
            parameters=data.get("parameters", {}),
            options=data.get("options", {})
        )
        
    def validate(self) -> None:
        """验证请求有效性
        
        Raises:
            ValueError: 请求无效
        """
        if not isinstance(self.action, MCPAction):
            raise ValueError(f"Invalid action: {self.action}")
            
        if self.action == MCPAction.QUERY and not self.query:
            raise ValueError("Query action requires query string")
            
        if not isinstance(self.parameters, dict):
            raise ValueError("Parameters must be a dictionary")
            
        if not isinstance(self.options, dict):
            raise ValueError("Options must be a dictionary")

@dataclass
class MCPResponse:
    """MCP 响应对象"""
    
    status: MCPStatus                           # 响应状态
    data: Optional[Any] = None                  # 响应数据
    metadata: Dict[str, Any] = field(default_factory=dict)  # 元数据
    error: Optional[str] = None                 # 错误信息
    
    def to_dict(self) -> Dict:
        """转换为字典格式"""
        return {
            "status": self.status.value,
            "data": self.data,
            "metadata": self.metadata,
            "error": self.error
        }
        
    @classmethod
    def from_dict(cls, data: Dict) -> "MCPResponse":
        """从字典创建响应对象"""
        return cls(
            status=MCPStatus(data["status"]),
            data=data.get("data"),
            metadata=data.get("metadata", {}),
            error=data.get("error")
        )
        
    def validate(self) -> None:
        """验证响应有效性
        
        Raises:
            ValueError: 响应无效
        """
        if not isinstance(self.status, MCPStatus):
            raise ValueError(f"Invalid status: {self.status}")
            
        if self.status == MCPStatus.ERROR and not self.error:
            raise ValueError("Error status requires error message")
            
        if not isinstance(self.metadata, dict):
            raise ValueError("Metadata must be a dictionary")

class MCPSerializer:
    """MCP 协议序列化器"""
    
    @staticmethod
    def serialize_request(request: MCPRequest) -> str:
        """序列化请求对象
        
        Args:
            request: MCP 请求对象
            
        Returns:
            str: JSON 字符串
        """
        return json.dumps(request.to_dict())
        
    @staticmethod
    def deserialize_request(data: str) -> MCPRequest:
        """反序列化请求对象
        
        Args:
            data: JSON 字符串
            
        Returns:
            MCPRequest: 请求对象
        """
        return MCPRequest.from_dict(json.loads(data))
        
    @staticmethod
    def serialize_response(response: MCPResponse) -> str:
        """序列化响应对象
        
        Args:
            response: MCP 响应对象
            
        Returns:
            str: JSON 字符串
        """
        return json.dumps(response.to_dict())
        
    @staticmethod
    def deserialize_response(data: str) -> MCPResponse:
        """反序列化响应对象
        
        Args:
            data: JSON 字符串
            
        Returns:
            MCPResponse: 响应对象
        """
        return MCPResponse.from_dict(json.loads(data))

class MCPVersion:
    """MCP 协议版本信息"""
    
    MAJOR = 1  # 主版本号
    MINOR = 0  # 次版本号
    PATCH = 0  # 补丁版本号
    
    @classmethod
    def get_version(cls) -> str:
        """获取版本字符串"""
        return f"{cls.MAJOR}.{cls.MINOR}.{cls.PATCH}"
        
    @classmethod
    def is_compatible(cls, version: str) -> bool:
        """检查版本兼容性
        
        Args:
            version: 版本字符串
            
        Returns:
            bool: 是否兼容
        """
        try:
            major, minor, patch = map(int, version.split("."))
            return major == cls.MAJOR  # 主版本号必须相同
        except ValueError:
            return False 